package com.cbgolf.oa.views;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.MyBaseAdapter;
import com.cbgolf.oa.base.BaseViewNew;
import com.cbgolf.oa.contract.IOrderDetailsContract.IOrderDetailsView;
import com.cbgolf.oa.contract.IOrderDetailsContract.IOrderDetailsWaiter;
import com.cbgolf.oa.event.EventOrder;
import com.cbgolf.oa.manager.DataManager;
import com.cbgolf.oa.manager.OrderManager;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.CollectionUtil;
import com.cbgolf.oa.util.DateUtil;
import com.cbgolf.oa.util.EnumUtil;
import com.cbgolf.oa.util.ImageLoaderUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.TypeUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.cbgolf.oa.viewbean.OrderBean;
import com.cbgolf.oa.viewbean.OrderBean.Item;
import com.cbgolf.oa.viewbean.OrderBean.Value;
import com.cbgolf.oa.widget.ListViewNew;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;
import com.zhy.base.adapter.ViewHolder;
import com.zhy.base.adapter.abslistview.CommonAdapter;
import java.util.List;
import java.util.Map;

/**
 * 订单详情 viewimp
 *
 * @author lq
 * @date 2018/4/12
 */

public class OrderDetailsViewImp extends BaseViewNew implements IOrderDetailsView {

  /**
   * top
   */
  @BindView(R.id.topBack_ll)
  View topBack;
  @BindView(R.id.title_tv)
  TextView titleTv;
  /**
   * 倒计时
   */
  @BindView(R.id.tv_orderdetails_timedwon)
  TextView timeDownTv;
  @BindView(R.id.vi_orderdetails_timedown_line)
  View timeDownLine;

  /**
   * teetime header
   */
  @BindView(R.id.ll_orderdetails_teetime_header_layout)
  View headerTeetime;
  @BindView(R.id.iv_orderdetails_teetime_header)
  ImageView logoTeetimeIv;
  @BindView(R.id.tv_orderdetails_teetime_header_parkname)
  TextView nameTeetimeTv;
  @BindView(R.id.tv_orderdetails_teetime_header_time)
  TextView timeTeetimeTv;
  @BindView(R.id.tv_orderdetails_teetime_header_personnum)
  TextView personNumTeetimeTv;
  @BindView(R.id.tv_orderdetails_teetime_header_state)
  TextView stateTeetimeTv;
  /**
   * match header
   */
  @BindView(R.id.ll_orderdetails_match_header_layout)
  View headerMatch;
  @BindView(R.id.iv_orderdetails_match)
  ImageView logoMatchIv;
  @BindView(R.id.tv_orderdetails_match_header_parkname)
  TextView nameMatchTv;
  @BindView(R.id.tv_orderdetails_match_header_time)
  TextView timeMatchTv;
  @BindView(R.id.tv_orderdetails_match_header_addrs)
  TextView addrsMatchTv;
  @BindView(R.id.tv_orderdetails_match_header_state)
  TextView stateMatchTv;
  @BindView(R.id.tv_orderdetails_match_header_groupname)
  TextView groupNameMatchTv;
  /**
   * hotel header
   */
  @BindView(R.id.ll_orderdetails_hotel_header_layout)
  View headerHotel;
  @BindView(R.id.iv_orderdetails_hotel_header)
  ImageView logoHotelIv;
  @BindView(R.id.tv_orderdetails_hotel_header_name)
  TextView nameHotelTv;
  @BindView(R.id.tv_orderdetails_hotel_header_time)
  TextView timeHotelTv;
  @BindView(R.id.tv_orderdetails_hotel_header_nights)
  TextView nightsHotelTv;
  @BindView(R.id.tv_orderdetails_hotel_header_state)
  TextView stateHotelTv;
  /**
   * combo header 住打
   */
  @BindView(R.id.ll_orderdetails_combo_header_layout)
  View headerCombo;
  @BindView(R.id.iv_orderdetails_combo_header)
  ImageView logoComboIv;
  @BindView(R.id.tv_orderdetails_combo_header_name)
  TextView nameComboTv;
  @BindView(R.id.tv_orderdetails_combo_header_time)
  TextView timeComboTv;
  @BindView(R.id.ll_orderdetails_combo_header_liveday)
  View nightsComboVi;
  @BindView(R.id.tv_orderdetails_combo_header_liveday)
  TextView nightsComboTv;
  @BindView(R.id.tv_orderdetails_combo_header_playcount)
  TextView playCountTv;
  @BindView(R.id.tv_orderdetails_combo_header_state)
  TextView stateComboTv;
  /**
   * money items
   */
  @BindView(R.id.tv_orderdetails_money_name)
  TextView moneyNameTv;
  @BindView(R.id.tv_orderdetails_money_all)
  TextView allMoneyTv;
  @BindView(R.id.listView)
  ListViewNew listView;
  /**
   * content
   */
  @BindView(R.id.couponTv)
  TextView couponTv;
  @BindView(R.id.valueTv)
  TextView valueTv;
  @BindView(R.id.payWayTv)
  TextView payWayTv;
  @BindView(R.id.realMoneyTv)
  TextView realMoneyTv;
  @BindView(R.id.linkView)
  View linkView;
  @BindView(R.id.linkNameTv)
  TextView linkNameTv;
  @BindView(R.id.linkPhoneTv)
  TextView linkPhoneTv;
  @BindView(R.id.orderSnTv)
  TextView orderSnTv;
  @BindView(R.id.orderTimeTv)
  TextView orderTimeTv;
  @BindView(R.id.codeView)
  View codeView;
  @BindView(R.id.codeTv)
  TextView codeTv;
  /**
   * yes or no
   */
  @BindView(R.id.ll_orderdetails_bottom_layout)
  View yesOrNoVi;
  @BindView(R.id.tv_orderdetails_yes)
  TextView yesTv;
  @BindView(R.id.tv_orderdetails_no)
  TextView noTv;
  /**
   * worker
   */
  private IOrderDetailsWaiter worker;
  /**
   * 订单类型
   */
  private int orderType;

  public OrderDetailsViewImp(Activity act, IOrderDetailsWaiter waiter, int type) {
    this.worker = waiter;
    this.orderType = type;
    ButterKnife.bind(this, act);
    super.init(act);
  }

  @Override
  protected void setViews() {
    ViewUtils.setText(titleTv, worker.getActivityTitle());
    switch (orderType) {
      case EnumUtil.BOOK:
        ViewUtils.setVisible(headerTeetime, true);
        break;
      case EnumUtil.MATCH:
        ViewUtils.setVisible(headerMatch, true);
        break;
      case EnumUtil.HOTEL:
        ViewUtils.setVisible(headerHotel, true);
        break;
      case EnumUtil.COMBO:
        ViewUtils.setVisible(headerCombo, true);
        break;
      default:
        ViewUtils.setVisible(headerTeetime, true);
        break;
    }
  }

  @Override
  protected void setListener() {
    ViewUtils.setClick(topBack, v -> worker.back());
    ViewUtils.setClick(yesTv, v -> worker.doSubmit());
    ViewUtils.setClick(noTv, v -> worker.doCancel());
  }


  /**
   * 展示数据
   */
  private void showData(OrderBean m) {
    if (orderType == 0) {
      orderType = EnumUtil.getOrderType(m.orderType);
    }
    switch (orderType) {
      case EnumUtil.BOOK:
        showTeetimeData(m);
        break;
      case EnumUtil.MATCH:
        showMatchData(m);
        break;
      case EnumUtil.HOTEL:
        showHotelData(m);
        break;
      case EnumUtil.COMBO:
        showComboData(m);
        break;
      default:
        showTeetimeData(m);
        break;
    }


  }

  /**
   * 展示住打数据
   */
  private void showComboData(OrderBean m) {
    ViewUtils.setVisible(headerCombo, true);
    ImageLoaderUtil.getImageLoader().displayImage(m.picSrc, logoComboIv);
    ViewUtils.setText(nameComboTv, m.courseName);
    ViewUtils.setText(timeComboTv, DateUtil.stampToDate(m.startTime, DateUtil.formatYMD));
    ViewUtils.setVisible(nightsComboVi, (!Util.isNull(m.liveDay) || !Util.isNull(m.playCount)));
    ViewUtils.setText(nightsComboTv, TextUtil.textNumInt(m.liveDay) + "夜");
    ViewUtils.setText(playCountTv, TextUtil.textNumInt(m.playCount) + "场球");
    ViewUtils.setText(stateComboTv, m.orderState);
    ViewUtils.setText(moneyNameTv, "套餐费用");
    setContentData(m);
    setComboItemList(m.orderItems);
    ViewUtils.setText(yesTv, "确认订单");
    ViewUtils.setText(noTv, "拒绝订单");
    ViewUtils.setVisible(yesOrNoVi, TextUtil.contains(m.orderState, "待确认")
        || TextUtil.contains(m.orderState, "已支付"));
    ViewUtils.setVisible(timeDownTv, TextUtil.contains(m.orderState, "待确认")
        || TextUtil.contains(m.orderState, "已支付"));
    ViewUtils.setVisible(timeDownLine, !(TextUtil.contains(m.orderState, "待确认")
        || TextUtil.contains(m.orderState, "已支付")));
//    ViewUtils.setVisible(timeDownTv,
//        (TypeUtil.parseLong(m.orderTime) + 15 * 60 * 1000 > System.currentTimeMillis()));
//    ViewUtils.setVisible(timeDownTv,
//        !(TypeUtil.parseLong(m.orderTime) + 10 * 60 * 1000 > System.currentTimeMillis()));
    ViewUtils.setHtmlText(timeDownTv, new StringBuilder()
        .append("<font color=\"#666666\">")
        .append("该订单球场在")
        .append("</font>")
        .append("<font color=\"#F74C31\">")
        .append("30分钟")
        .append("</font>")
        .append("<font color=\"#666666\">")
        .append("内确认是否接单")
        .append("</font>").toString());

  }

  /**
   * 展示酒店数据
   */
  private void showHotelData(OrderBean m) {
    ViewUtils.setVisible(headerHotel, true);
    ImageLoaderUtil.getImageLoader().displayImage(m.picSrc, logoHotelIv);
    ViewUtils.setText(nameHotelTv, m.hotelName);
    ViewUtils.setText(timeHotelTv,
        null != m.dayRange ? (DateUtil.stampToDate(m.dayRange.start, DateUtil.formatMD_Zh) + "-"
            + DateUtil.stampToDate(m.dayRange.end, DateUtil.formatMD_Zh))
            : "");
    ViewUtils.setText(nightsHotelTv, null != m.dayRange ? ("共"
        + ((TypeUtil.parseLong(m.dayRange.end) - TypeUtil.parseLong(m.dayRange.start))
        / DateUtil.getOneDay()) + "晚")
        : "");
    ViewUtils.setText(moneyNameTv, "房间费用");
    ViewUtils.setText(stateHotelTv, m.orderState);
    setContentData(m);
    setHotelItemList(m.orderItems);
    ViewUtils.setText(yesTv, "确认入住");
    ViewUtils.setText(noTv, "取消入住");
    ViewUtils.setVisible(yesOrNoVi, TextUtil.contains(m.orderState, "待确认")
        || TextUtil.contains(m.orderState, "已支付"));
    ViewUtils.setVisible(timeDownTv, TextUtil.contains(m.orderState, "待确认")
        || TextUtil.contains(m.orderState, "已支付"));
    ViewUtils.setVisible(timeDownLine, !(TextUtil.contains(m.orderState, "待确认")
        || TextUtil.contains(m.orderState, "已支付")));
    ViewUtils.setHtmlText(timeDownTv, new StringBuilder()
        .append("<font color=\"#666666\">")
        .append("该订单酒店会在")
        .append("</font>")
        .append("<font color=\"#F74C31\">")
        .append("15分钟")
        .append("</font>")
        .append("<font color=\"#666666\">")
        .append("内确认是否接单")
        .append("</font>").toString());
  }

  /**
   * 展示比赛数据
   */
  private void showMatchData(OrderBean m) {
    ViewUtils.setVisible(headerMatch, true);
    ImageLoaderUtil.getImageLoader().displayImage(m.logoUrl, logoMatchIv);
    ViewUtils.setText(nameMatchTv, m.competitionName);
    ViewUtils.setText(addrsMatchTv, m.courseName);
    ViewUtils.setText(timeMatchTv, m.openDatetime);
    ViewUtils.setText(groupNameMatchTv,
        (null != m.goodsInfo) ? m.goodsInfo.goodsName : m.groupName);
    ViewUtils.setText(stateMatchTv, OrderManager.getOrderState(m.orderState));
    ViewUtils.setText(moneyNameTv, "报名费用");
    setContentData(m);
    setMatchItemList(m.playCustomerInfoList);
    ViewUtils.setText(payWayTv, m.payType);
    ViewUtils.setText(realMoneyTv, new StringBuilder().append("￥")
        .append(TextUtil.textNumFloat(m.totalPrice)));

  }

  /**
   * 展示TEETIME数据
   */
  private void showTeetimeData(OrderBean m) {
    ViewUtils.setVisible(headerTeetime, true);
    ImageLoaderUtil.getImageLoader().displayImage(m.picSrc, logoTeetimeIv);
    ViewUtils.setText(nameTeetimeTv, m.courseName);
    ViewUtils.setText(timeTeetimeTv, DateUtil.stampToDate(m.startTime));
    ViewUtils.setText(personNumTeetimeTv, TextUtil.textNumInt(m.personNumber) + "人");
    ViewUtils.setText(stateTeetimeTv, m.orderState);
    ViewUtils.setText(moneyNameTv, "预定费用");
    setContentData(m);
    setTeetimeItemList(m.caddies);
  }

  /**
   * 展示公共部分数据
   */
  private void setContentData(OrderBean m) {
    ViewUtils.setText(allMoneyTv,
        "￥" + TextUtil.textNumFloat(m.totalPrice));
    ViewUtils.setText(couponTv,
        new StringBuilder()
            .append("￥")
            .append(TextUtil.textNumFloat(TypeUtil.parseFloat(m.cbPrice)
                + TypeUtil.parseFloat(m.coursePrice) + TypeUtil.parseFloat(m.couponPrice))));
    if (!Util.listIsNull(m.orderValueCardDtoList)) {
      setValueCard(m.orderValueCardDtoList);
    } else {
      ViewUtils.setText(valueTv, new StringBuilder().append("￥")
          .append(TextUtil.textNumFloat(null)));
    }
    ViewUtils.setText(payWayTv, m.usedPayType);
    ViewUtils.setText(realMoneyTv, new StringBuilder().append("￥")
        .append(TextUtil.textNumFloat(m.realityPrice)));
    setLinkName(m);
    ViewUtils.setVisible(codeView,
        (!Util.isEquals("已退订", m.orderState)
            && !Util.isEquals("已取消", m.orderState)
            && !Util.isNull(m.verificationCode)));
    ViewUtils.setText(codeTv, TextUtil.getBankNumFormat(m.verificationCode));
    ViewUtils.setText(orderSnTv, m.orderSn);
    ViewUtils.setText(orderTimeTv, DateUtil.stampToDate(m.orderTime));
  }

  /**
   * 展示联系人
   */
  private void setLinkName(OrderBean m) {
    String linkName = null;
    String linkPhone = null;
    if (!CollectionUtil.mapIsNull(m.contact)) {
      for (Map.Entry<String, String> me : m.contact.entrySet()) {
        linkName = me.getKey();
        linkPhone = me.getValue();
        break;
      }
    }
    if (Util.isNull(linkName) && Util.isNull(linkPhone)
        && !Util.listIsNull(m.customerInfoList)) {
      Map<String, String> linkMap = m.customerInfoList.get(0);
      if (!CollectionUtil.mapIsNull(linkMap)) {
        for (Map.Entry<String, String> me : linkMap.entrySet()) {
          linkName = me.getKey();
          linkPhone = me.getValue();
          break;
        }
      }
    }
    if (Util.isNull(linkName) && Util.isNull(linkPhone) && null != m.customer) {
      linkName = m.customer.name;
      linkPhone = m.customer.mobileId;
    }
    ViewUtils.setVisible(linkView, !Util.isNull(linkName) || !Util.isNull(linkPhone));
    ViewUtils.setText(linkNameTv, linkName);
    ViewUtils.setText(linkPhoneTv, linkPhone);
  }

  /**
   * 展示储值
   */
  private void setValueCard(List<Value> list) {
    float valueMoney = 0;
    for (int i = 0; i < list.size(); i++) {
      valueMoney += TypeUtil.parseFloat(list.get(i).balance);
    }
    ViewUtils.setText(valueTv, new StringBuilder().append("￥")
        .append(TextUtil.getDoubleFormat(valueMoney, 2)).toString());
  }

  /**
   * 住打套餐 商品列表
   *
   * @param list 商品列表
   */
  private void setComboItemList(List<Item> list) {
    setHotelItemList(list);
  }

  /**
   * 酒店 商品列表
   *
   * @param list 商品列表
   */
  private void setHotelItemList(List<Item> list) {
    if (Util.listIsNull(list)) {
      return;
    }
    listView.setDividerHeight(0);
    ViewUtils.setVisible(listView, true);
    MyBaseAdapter<Item> adapter = new MyBaseAdapter<OrderBean.Item>(
        R.layout.listitem_orderdetails_hotel, context, list) {
      @Override
      public View getView(int position, View view, ViewGroup parent, OrderBean.Item item) {
        if (null == item) {
          return view;
        }
        setText(R.id.nameTv, item.productName);
        setText(R.id.breakFastTv, DateUtil.stampToDate(item.confirmTime, DateUtil.formatYMD));
        setText(R.id.priceTv, "￥" + TextUtil.textNumFloat(item.price) + "x"
            + TextUtil.textNumInt(item.quantity));
        return view;
      }
    };
    listView.setAdapter(adapter);
  }

  /**
   * 比赛 商品列表
   *
   * @param list 商品列表
   */
  private void setMatchItemList(List<OrderBean.mem> list) {
    if (Util.listIsNull(list)) {
      return;
    }
    CommonAdapter<OrderBean.mem> adapter = new CommonAdapter<OrderBean.mem>(context,
        R.layout.listitem_ordertails_match, list) {
      @Override
      public void convert(ViewHolder holder, OrderBean.mem mem) {
        if (null == mem) {
          return;
        }
        holder.setText(R.id.item_mem_match_name_tv, TextUtil.Text(mem.name));
        holder
            .setText(R.id.item_mem_match_phone_tv, Util.isPhone(mem.mobileId) ? mem.mobileId : "");
        holder.setText(R.id.item_mem_match_money_tv, TextUtil.textNumFloat(mem.price));
        AutoUtil.auto(holder.getConvertView());
      }
    };
    listView.setAdapter(adapter);
    listView.setDividerHeight(0);
    ViewUtils.setVisible(listView, true);
  }

  /**
   * teetime  打球人列表
   */
  private void setTeetimeItemList(List<OrderBean.caddie> listMems) {
    if (Util.listIsNull(listMems)) {
      return;
    }
    CommonAdapter<OrderBean.caddie> adapter
        = new CommonAdapter<OrderBean.caddie>(context, R.layout.item_mem, listMems) {
      @Override
      public void convert(ViewHolder holder, OrderBean.caddie caddie) {
        if (null == caddie) {
          return;
        }
        holder.setText(R.id.item_mem_name_tv, TextUtil.Text(caddie.coustomerName))
            .setText(R.id.item_mem_dingchang_money_tv,
                "￥" + TextUtil.textNumFloat(caddie.coustomerPrice));
        if (null == caddie.orderCaddie) {
          return;
        }
        holder.setText(R.id.item_mem_qiutong_money_tv,
            "￥" + TextUtil.textNumFloat(caddie.orderCaddie.fee))
            .setText(R.id.item_mem_qiutong_tv,
                Util.isNull(caddie.orderCaddie.name) ? "默认球僮" :
                    (!Util.isNull(caddie.orderCaddie.levelName) ?
                        new StringBuilder()
                            .append(caddie.orderCaddie.name)
                            .append(caddie.orderCaddie.levelName)
                            .append("级").toString() :
                        caddie.orderCaddie.name));
      }
    };
    ViewUtils.setVisible(listView, true);
    listView.setAdapter(adapter);
  }


  @Override
  public void requestOver(EventOrder event) {
    if (null == event) {
      return;
    }
    stopProgress();
    switch (event.target) {
      case DataManager.ORDER_DETAILS:
        if (null == event.orderBean) {
          requestFail(event.errorMsg, event.errorCode);
          return;
        }
        showData(event.orderBean);
        break;
      case DataManager.ORDER_DETAILS_CANCEL:
        showCancelOrConfirmResult(false, event.isCancelSuccess, event.isHotelOrder, event.errorMsg);
        break;
      case DataManager.ORDER_DETAILS_CONFIRM:
        showCancelOrConfirmResult(true, event.isConfirmSuccess, event.isHotelOrder, event.errorMsg);
        break;
      default:
        break;
    }

  }

  /**
   * 取消或确认结果
   */
  private void showCancelOrConfirmResult(boolean isSubmit, boolean isSuccess, boolean isHotelOrder,
      String errorMsg) {
    if (!isSuccess) {
      Util.show(errorMsg);
      return;
    }
    if (isSubmit) {
      Util.show("订单确认成功");
    } else {
      Util.show(new StringBuilder()
          .append("订单")
          .append(isHotelOrder ? "已取消" : "已拒绝")
          .toString());
    }

  }

  @Override
  public void showProgress() {
    AnimaUtil.showLoading(context);
  }

  @Override
  public void stopProgress() {
    AnimaUtil.stopLoading();
  }

  @Override
  public void requestFail(String msg, int code) {
    Util.show(msg);
  }

}

